package com.jdk.demo.asynchronousFileChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Read {

	public static void main(String[] args) throws Exception {
		Path path = Paths.get("E:/zsl/temp2.txt");
		Set<StandardOpenOption> set = new HashSet<>();
		set.add(StandardOpenOption.READ);
		ExecutorService executor = Executors.newFixedThreadPool(10);
		AsynchronousFileChannel fileChannel =  AsynchronousFileChannel.open(path, set, executor, new FileAttribute[0]);
		Path pathW = Paths.get("E:/zsl/temp3.txt");
		AsynchronousFileChannel fileChannelW = AsynchronousFileChannel.open(pathW, StandardOpenOption.WRITE);

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		long position = 0;
		fileChannel.read(buffer, position, null, new CompletionHandler<Integer, ByteBuffer>() {
		    @Override
		    public void completed(Integer result, ByteBuffer attachment) {
		        buffer.flip();
		        fileChannelW.write(buffer, 0, null, new CompletionHandler<Integer, ByteBuffer>() {
					@Override
					public void completed(Integer result, ByteBuffer attachment) {
						buffer.clear();
				        System.out.println("Write done. result: " + result);
					}
					@Override
					public void failed(Throwable exc, ByteBuffer attachment) {

					}
		        });
		    }
		    @Override
		    public void failed(Throwable exc, ByteBuffer attachment) {

		    }
		});
		Thread.sleep(10000000);
	}

}
